// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {gameData} from "./GameData";
import NewItem from "./NewItem";
import show = cc.show;

const {ccclass, property} = cc._decorator;

@ccclass
export default class ListCtrl extends cc.Component {

  @property(cc.Node)
  content: cc.Node = null;
  @property(cc.Prefab)
  itemTemplate: cc.Prefab = null;

  private items: Array<any> = [];

  // LIFE-CYCLE CALLBACKS:

  onLoad() {
    for (let i = 0; i < 10; i++) {
      let item = cc.instantiate(this.itemTemplate);
      this.items.push(item)
    }
  }

  init(length: number) {
    const list = gameData.rankList;
    const showList = list.slice(list.length - length, list.length).reverse();
    this.content.removeAllChildren()
    showList.forEach((value, index) => {
      const node = this.getItem();
      node.getComponent(NewItem).updateItem(index, value);
      node.parent = this.content
    })
  }

  getItem(): cc.Node {
    if (this.items.length > 0) {
      return this.items.shift();
    }
    return cc.instantiate(this.itemTemplate);
  }

  // update (dt) {}
}
